package com.sita.persistence;

import com.colintmiller.simplenosql.DataFilter;
import com.colintmiller.simplenosql.NoSQL;
import com.colintmiller.simplenosql.NoSQLEntity;
import com.colintmiller.simplenosql.RetrievalCallback;
import com.sita.bike.rest.model.Account;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.tboard.ui.tools.L;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by xiaodong on 16/2/24.
 */
public class BlacklistHelper {
    public static void addToBlacklist(Account account) {
        NoSQLEntity<Account> entity = new NoSQLEntity<Account>(Constants.RT_BLACKLIST_BUCKET, account.mAccountId, account);
        NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class).save(entity);
    }

    public static boolean isInBlacklist(final String accountId) {
        final AtomicBoolean hasBlacklist = new AtomicBoolean(false);
        final CountDownLatch latch = new CountDownLatch(1);
        NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class)
                .bucketId(Constants.RT_BLACKLIST_BUCKET)
                .filter(new DataFilter<Account>() {
                    @Override
                    public boolean isIncluded(NoSQLEntity<Account> item) {
                        if (accountId.equals(item.getData().mAccountId)) {
                            return true;
                        }
                        return false;
                    }
                })
                .retrieve(new RetrievalCallback<Account>() {
                    @Override
                    public void retrievedResults(List<NoSQLEntity<Account>> noSQLEntities) {
                        latch.countDown();
                        if (noSQLEntities != null && !noSQLEntities.isEmpty()){
                            hasBlacklist.set(true);
                        }
                    }
                });
        try {
            latch.await(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            L.e(e);
        }
        return hasBlacklist.get();
    }
}
